<?php

namespace app\model;

//use support\Model;
use app\controller\wmapi\IndexController;
use app\controller\wmapi\order\OrderController;
use app\controller\wmapi\PublicCommentController;
use support\Db;
use Illuminate\Database\Eloquent\Model;
use function GuzzleHttp\json_decode;

class WaOrders
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'wa_orders_sales';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    public static function allByLike($condition,$con_one,$con_two,$con_three,$con_four)
    {
        $condition [] = ['is_show','=',1];
        $list = Db::table('wa_orders_sales')
            ->select('*')
            ->where($condition)
            ->get();
        if ($list){
            foreach ($list as $kk => $k){
                $con_one ['order_sn_parent'] = $k->order_sn;
                $con_two ['order_sn_parent'] = $k->order_sn;
                $con_three ['order_sn_parent'] = $k->order_sn;
                $con_four ['order_sn_parent'] = $k->order_sn;

                $specs_can = WaOrdersRelevance::allByMoreLike($con_one,$con_two,$con_three,$con_four);
                $specs_can = json_decode($specs_can);
                $k->specs_can = $specs_can;
                if (!$specs_can){
                    unset($list[$kk]);
                }

                if ($k->user_id){
                    $user = WaMembers::find(['id' => $k->user_id]);
                    $user = json_decode($user);
                    $k->user_type = $user->type;
                    // 1 个人 2 企业
                    if ($k->user_type == 1){
                        $k->user_type_name = '个人';
                    }elseif ($k->user_type == 2){
                        $k->user_type_name = '企业';
                    }
                    $k->user_passport_number = $user->passport_number;
                    $k->user_business_license_number = $user->business_license_number;
                }else{
                    $k->user_type = '';
                    $k->user_type_name = '';
                    $k->user_passport_number = '';
                    $k->user_business_license_number = '';
                }

                $k->status_name = IndexController::saleOrderStatusName($k->status);


                // 订单类型 1 预售待采购 2 库存待销售 3部分预售单（两者都有）
                if ($k->orders_type == 1){
                    $k->orders_type_name = '预售待采购';
                }elseif ($k->orders_type == 2){
                    $k->orders_type_name = '库存待销售';
                }elseif ($k->orders_type == 3){
                    $k->orders_type_name = '部分预售单';
                }else{
                    $k->orders_type_name = '';
                }


                $k->condition_name = IndexController::conditionName($k->condition);

                $k->currency_name = IndexController::currencyNameCommon($k->currency);


            }
        }

        return json_encode($list);
    }

    public static function alls($condition)
    {
        $condition [] = ['is_show','=',1];
        $list = Db::table('wa_orders_sales')
            ->select('*')
            ->where($condition)
            ->get();
        if ($list){
            foreach ($list as $k){

                $specs_can = WaOrdersRelevance::all([['order_sn_parent','=',$k->order_sn]]);
                $specs_can = json_decode($specs_can);
                $k->specs_can = $specs_can;


                if ($k->user_id){
                    $user = WaMembers::find(['id' => $k->user_id]);
                    $user = json_decode($user);
                    $k->user_type = $user->type;
                    // 1 个人 2 企业
                    if ($k->user_type == 1){
                        $k->user_type_name = '个人';
                    }elseif ($k->user_type == 2){
                        $k->user_type_name = '企业';
                    }
                    $k->user_passport_number = $user->passport_number;
                    $k->user_business_license_number = $user->business_license_number;
                }else{
                    $k->user_type = '';
                    $k->user_type_name = '';
                    $k->user_passport_number = '';
                    $k->user_business_license_number = '';
                }


                $k->status_name = IndexController::saleOrderStatusName($k->status);

                // 订单类型 1 预售待采购 2 库存待销售 3部分预售单（两者都有）
                if ($k->orders_type == 1){
                    $k->orders_type_name = '预售待采购';
                }elseif ($k->orders_type == 2){
                    $k->orders_type_name = '库存待销售';
                }elseif ($k->orders_type == 3){
                    $k->orders_type_name = '部分预售单';
                }else{
                    $k->orders_type_name = '';
                }


                $k->condition_name = IndexController::conditionName($k->condition);

                $k->currency_name = IndexController::currencyNameCommon($k->currency);
                $sum_data = WaAccountingInformationRelevance::billDetailsByOrderSn($k->order_sn);
                if ($sum_data){
                    $sum_data = json_decode(WaAccountingInformationRelevance::billDetailsByOrderSn($k->order_sn));
                }
                $k->sum_data = $sum_data;
            }
        }

        return json_encode($list);
    }

    public static function allsByWhereIn($condition,$whereIn)
    {
        $condition [] = ['is_show','=',1];
        $list = Db::table('wa_orders_sales')
            ->select('*')
            ->where($condition)
            ->whereIn('status',$whereIn)
            ->get();
        if ($list){
            foreach ($list as $k){

                $specs_can = WaOrdersRelevance::all([['order_sn_parent','=',$k->order_sn]]);
                $specs_can = json_decode($specs_can);
                $k->specs_can = $specs_can;


                if ($k->user_id){
                    $user = WaMembers::find(['id' => $k->user_id]);
                    $user = json_decode($user);
                    $k->user_type = $user->type;
                    // 1 个人 2 企业
                    if ($k->user_type == 1){
                        $k->user_type_name = '个人';
                    }elseif ($k->user_type == 2){
                        $k->user_type_name = '企业';
                    }
                    $k->user_passport_number = $user->passport_number;
                    $k->user_business_license_number = $user->business_license_number;
                }else{
                    $k->user_type = '';
                    $k->user_type_name = '';
                    $k->user_passport_number = '';
                    $k->user_business_license_number = '';
                }


                $k->status_name = IndexController::saleOrderStatusName($k->status);

                // 订单类型 1 预售待采购 2 库存待销售 3部分预售单（两者都有）
                if ($k->orders_type == 1){
                    $k->orders_type_name = '预售待采购';
                }elseif ($k->orders_type == 2){
                    $k->orders_type_name = '库存待销售';
                }elseif ($k->orders_type == 3){
                    $k->orders_type_name = '部分预售单';
                }else{
                    $k->orders_type_name = '';
                }


                $k->condition_name = IndexController::conditionName($k->condition);

                $k->currency_name = IndexController::currencyNameCommon($k->currency);
                $sum_data = WaAccountingInformationRelevance::billDetailsByOrderSn($k->order_sn);
                if ($sum_data){
                    $sum_data = json_decode(WaAccountingInformationRelevance::billDetailsByOrderSn($k->order_sn));
                }
                $k->sum_data = $sum_data;


                WaOrders::deepositBalanceAccInfo($k,$funds_acc_info_by_deep_bala);
                $k->funds_acc_info_by_deep_bala = $funds_acc_info_by_deep_bala;
            }
        }

        return json_encode($list);
    }

    public static function ordersCount($start_time,$end_time)
    {

        $start_time = date('Y-m-d H:i:s', $start_time);
        $end_time = date('Y-m-d H:i:s', $end_time);
        $provider_count =Db::table('wa_orders_sales')
            ->select('*')
            ->where('post_type','product')
            ->whereBetween('created_at',[$start_time,$end_time])
            ->count(); // 用户数量
        return $provider_count;

    }

    public static function ordersCountByAdmin($start_time,$end_time,$adminId)
    {

        $start_time = date('Y-m-d H:i:s', $start_time);
        $end_time = date('Y-m-d H:i:s', $end_time);
        $provider_count =Db::table('wa_orders_sales')
            ->select('*')
            ->where('admin_id',$adminId->id)
            ->whereBetween('created_at',[$start_time,$end_time])
            ->count(); // 用户数量
        return $provider_count;

    }

    public static function created($data){
        $result = Db::table('wa_orders_sales')->insertGetId($data);
        return $result;
    }

    public static function updated($data,$where){
        $result = Db::table('wa_orders_sales')->where($where)->update($data);
        return $result;
    }


    public static function list($adminId,$page, $pageNum, $whereIn,$whereNotIn,$fields = ['*'], $whereStatusIn = [], $condition = [], $between = []){
        $condition [] = ['is_show','=',1];
        $offset = ($page - 1) * $pageNum;
//        if ($between) {
//            if ($whereIn){
//                $model = Db::table('wa_orders_sales')
//                    ->select($fields)
//                    ->where($condition)
//                    ->whereIn('admin_id',$whereIn)
//                    ->whereNotIn('status',$whereNotIn)
////                ->where(['admin.status', '!=', 4])
//                    ->whereBetween('created_at', $between);
//            }else{
//                $model = Db::table('wa_orders_sales')
//                    ->select($fields)
//                    ->where($condition)
//                    ->whereNotIn('status',$whereNotIn)
////                ->where(['admin.status', '!=', 4])
//                    ->whereBetween('created_at', $between);
//            }
//
//        }
//        else {
//            if ($whereIn){
//                $model = Db::table('wa_orders_sales')
//                    ->select($fields)
////                ->where(['orders_status', '!=', 4])
//                    ->where($condition)
//                    ->whereIn('admin_id',$whereIn)
//                    ->whereNotIn('status',$whereNotIn);
//            }else{
//                $model = Db::table('wa_orders_sales')
//                    ->select($fields)
////                ->where(['orders_status', '!=', 4])
//                    ->where($condition)
//                    ->whereNotIn('status',$whereNotIn);
//            }
//
//        }

        $model = Db::table('wa_orders_sales')
            ->select($fields)
            ->where($condition);
        if ($between) {
            $model->whereBetween('created_at', $between);
        }
        if ($whereIn) {
            $model->whereIn('admin_id',$whereIn);
        }

        if ($whereStatusIn) {
            $model->whereIn('status',$whereStatusIn);
        }
        if ($whereNotIn) {
            $model->whereNotIn('status',$whereNotIn);
        }


        $count = $model->count();
        $list = $model
            ->orderBy('id', 'desc')
            ->offset($offset)
            ->limit($pageNum)
            ->get();
        if ($list){
            foreach ($list as $k){

                if ($k->pi){
                    $k->pi = json_decode($k->pi);
                }
                $counts = WaOrdersRelevance::counts(['order_sn_parent' => $k->order_sn]);
                $sum = WaOrdersRelevance::sums(['order_sn_parent' => $k->order_sn]);
                $k->totalPrice = $sum;
                $k->deposit_price = $k->deeposit_amount; // 定金
                if($k->deposit_price){
                    $k->balancePrice = round($k->totalPrice,2) - round($k->deposit_price,2); // 余款
                }else{
                    $k->balancePrice = round($k->totalPrice,2); // 余款
                }

                // 查看定金      计算余款
                $order_log=  WaOrdersOperateLog::find(['*'],['order_sn_parent' => $k->order_sn,'type' => 1]);
                $order_log = json_decode($order_log);
                if ($order_log){
                    $result =  round($sum,2) - round($order_log->this_request_price,2);  // 待支付余款
                    $k->balancePrice = round($result,2);
                    $k->deposit_price = round($order_log->this_request_price,2);
                }


                //定金
                if (!$k->deeposit_amount){
                    $k->deeposit_amount = 0.00;
                }else{
                    $k->deeposit_amount = round($k->deeposit_amount,2);
                }
                //尾款
                $k->balance_amount  = round($k->total_amount,2) - round($k->deeposit_amount,2);

                // 定金的状态 定金未到账  定金未足额到账 定金足额到账
                $sales_fund_deposit_type_condition = [];
                $sales_fund_deposit_type_condition [] = ['order_sn_parent','=',$k->order_sn]; //
                $sales_fund_deposit_type_condition [] = ['type','=',1]; // 定金
                $sales_fund_deposit_type_where_in = [0,1]; // 待审批和通过审批
                $deposit_acc_price = WaAccountingInformationRelevance::sumsBySaesFundType($sales_fund_deposit_type_condition, $sales_fund_deposit_type_where_in);


                if (!$deposit_acc_price){
                    $k->deposit_acc_status = 1;
                    $k->deposit_acc_status_name = '未到账';
                }elseif(round($deposit_acc_price,2)>0){
                    if (round($deposit_acc_price,2) == $k->deeposit_amount){
                        $k->deposit_acc_status = 2;
                        $k->deposit_acc_status_name = '足额到账';
                    }else{
                        $k->deposit_acc_status = 3;
                        $k->deposit_acc_status_name = '未足额到账';

                    }
                }
                // 尾款的状态 尾款未到账  尾款未足额到账 尾款足额到账
                PublicCommentController::账单分配状态;
                PublicCommentController::销售订单到账状态;
                $sales_fund_balance_type_condition = [];
                $sales_fund_balance_type_condition [] = ['order_sn_parent','=',$k->order_sn]; //
                $sales_fund_balance_type_condition [] = ['type','=',2]; // 尾款
                $sales_fund_balance_type_where_in = [0,1]; // 待审批和通过审批
                $balance_acc_price= WaAccountingInformationRelevance::sumsBySaesFundType($sales_fund_balance_type_condition, $sales_fund_balance_type_where_in);
                if (!$balance_acc_price){
                    $k->balance_acc_status = 1;
                    $k->balance_acc_status_name = '未到账';
                }elseif(round($balance_acc_price,2)>0){
                    if (round($balance_acc_price,2) == $k->deeposit_amount){
                        $k->balance_acc_status = 2;
                        $k->balance_acc_status_name = '足额到账';

                    }else{
                        $k->balance_acc_status = 3;
                        $k->balance_acc_status_name = '未足额到账';
                    }
                }


                $k->counts = $counts;
                // 订单状态
                PublicCommentController::销售订单状态;
                $k->status_name = IndexController::saleOrderStatusName($k->status);

                if ($k->status == 12){
                    $k->status_name = '待财务确认定金到账';
                    $wai = WaAccountingInformation::find(['order_sn_parent' => $k->order_sn, 'type' => 1]);
                    $wai = json_decode($wai);
                    if ($wai){
                        if ($wai->status == 1){
                            $wai->accounting_information_status = 1;
                            $k->accounting_information_status_name = '待财务确认(定金)';
                        }elseif ($wai->status == 2){
                            $wai->accounting_information_status = 2;
                            $k->accounting_information_status_name = '财务已确认(定金)';
                        }elseif ($wai->status == 3){
                            $wai->accounting_information_status = 3;
                            $k->accounting_information_status_name = '到账异常(定金)';
                            $k->exception_reason = $wai->exception_reason;
                        }else{
                            $wai->accounting_information_status = '';
                            $k->accounting_information_status_name = '';
                        }
                    }
                }

                if ($k->status == 16){
                    $k->status_name = '待财务确认余款到账';
                    $wai = WaAccountingInformation::find(['order_sn_parent' => $k->order_sn, 'type' => 2]);
                    $wai = json_decode($wai);
                    if ($wai){
                        if ($wai->status == 1){
                            $wai->accounting_information_status = 1;
                            $k->accounting_information_status_name = '待财务确认(余款)';
                        }elseif ($wai->status == 2){
                            $wai->accounting_information_status = 2;
                            $k->accounting_information_status_name = '财务已确认(余款)';
                        }elseif ($wai->status == 3){
                            $wai->accounting_information_status = 3;
                            $k->accounting_information_status_name = '到账异常(余款)';
                            $k->exception_reason = $wai->exception_reason;
                        }else{
                            $wai->accounting_information_status = '';
                            $k->accounting_information_status_name = '';
                        }
                    }
                }



                // 订单类型 1 预售待采购 2 库存待销售 3部分预售单（两者都有）
                if ($k->orders_type == 1){
                    $k->orders_type_name = '预售待采购';
                }elseif ($k->orders_type == 2){
                    $k->orders_type_name = '库存待销售';
                }elseif ($k->orders_type == 3){
                    $k->orders_type_name = '部分预售单';
                }else{
                    $k->orders_type_name = '';
                }


                $k->condition_name = IndexController::conditionName($k->condition);//交易条件

                $k->currency_name = IndexController::currencyNameCommon($k->currency);// 货币名称


            }
        }
        return json_encode(['list' => $list, 'count' => $count]);


    }

    //定金 尾款  账单分配金额
    public static function deepositBalanceAccInfo($sales_order_data,&$funds_acc_info_by_deep_bala){
        $k = $sales_order_data; // 销售订单信息
        $counts = WaOrdersRelevance::counts(['order_sn_parent' => $k->order_sn]);
        $sum = WaOrdersRelevance::sums(['order_sn_parent' => $k->order_sn]);
        $k->totalPrice = $sum;
        $k->deposit_price = $k->deeposit_amount; // 定金
        if($k->deposit_price){
            $k->balancePrice = round($k->totalPrice,2) - round($k->deposit_price,2); // 余款
        }else{
            $k->balancePrice = round($k->totalPrice,2); // 余款
        }

        // 查看定金      计算余款
        $order_log=  WaOrdersOperateLog::find(['*'],['order_sn_parent' => $k->order_sn,'type' => 1]);
        $order_log = json_decode($order_log);
        if ($order_log){
            $result =  round($sum,2) - round($order_log->this_request_price,2);  // 待支付余款
            $k->balancePrice = round($result,2);
            $k->deposit_price = round($order_log->this_request_price,2);
        }


        //定金
        if (!$k->deeposit_amount){
            $k->deeposit_amount = 0.00;
        }else{
            $k->deeposit_amount = round($k->deeposit_amount,2);
        }
        //尾款
        $k->balance_amount  = round($k->total_amount,2) - round($k->deeposit_amount,2);

        // 定金的状态 定金未到账  定金未足额到账 定金足额到账
        $sales_fund_deposit_type_condition = [];
        $sales_fund_deposit_type_condition [] = ['order_sn_parent','=',$k->order_sn]; //
        $sales_fund_deposit_type_condition [] = ['type','=',1]; // 定金
        $sales_fund_deposit_type_where_in = [0,1]; // 待审批和通过审批
        $deposit_acc_price = WaAccountingInformationRelevance::sumsBySaesFundType($sales_fund_deposit_type_condition, $sales_fund_deposit_type_where_in);


        if (!$deposit_acc_price){
            $k->deposit_acc_status = 1;
            $k->deposit_acc_status_name = '未到账';
        }elseif(round($deposit_acc_price,2)>0){
            if (round($deposit_acc_price,2) == $k->deeposit_amount){
                $k->deposit_acc_status = 2;
                $k->deposit_acc_status_name = '足额到账';
            }else{
                $k->deposit_acc_status = 3;
                $k->deposit_acc_status_name = '未足额到账';
            }
        }
        // 尾款的状态 尾款未到账  尾款未足额到账 尾款足额到账
        $sales_fund_balance_type_condition = [];
        $sales_fund_balance_type_condition [] = ['order_sn_parent','=',$k->order_sn]; //
        $sales_fund_balance_type_condition [] = ['type','=',2]; // 尾款
        $sales_fund_balance_type_where_in = [0,1]; // 待审批和通过审批
        $balance_acc_price= WaAccountingInformationRelevance::sumsBySaesFundType($sales_fund_balance_type_condition, $sales_fund_balance_type_where_in);
        if (!$balance_acc_price){
            $k->balance_acc_status = 1;
            $k->balance_acc_status_name = '未到账';
        }elseif(round($balance_acc_price,2)>0){
            if (round($balance_acc_price,2) == $k->deeposit_amount){
                $k->balance_acc_status = 2;
                $k->balance_acc_status_name = '足额到账';
            }else{
                $k->balance_acc_status = 3;
                $k->balance_acc_status_name = '未足额到账';
            }
        }
        $funds_acc_info_by_deep_bala = [
            'deeposit_amount' => $k->deeposit_amount, // 总定金
            'deposit_acc_price' => $deposit_acc_price, // 已分配定金额度
            'deposit_acc_status' => $k->deposit_acc_status, // 定金分配额度状态
            'deposit_acc_status_name' => $k->deposit_acc_status_name, // 定金分配额度状态名称
            'balance_acc_status' => $k->balance_acc_status, // 尾款分配额度状态
            'balance_acc_status_name' => $k->balance_acc_status_name, // 尾款分配额度状态名称
            'balance_amount' => $k->balance_amount, // 总尾款
            'balance_acc_price' => $balance_acc_price, // 已分配尾款额度
        ];
    }

    public static function find($condition)
    {
        $res = Db::table('wa_orders_sales')
            ->where($condition)
            ->first();
        if ($res) {
            $k = $res;
            if ($k) {

                if ($k->transfer_export_company_account) {

                    $k->transfer_export_company_account = json_decode($k->transfer_export_company_account);
                }else{
                    $k->transfer_export_company_account = '';
                }

                $sum = WaOrdersRelevance::sums(['order_sn_parent' => $k->order_sn]);
                $k->totalPrice = $sum;
                $k->deposit_price = $k->deeposit_amount; // 定金
                if($k->deposit_price){
                    $k->balancePrice = round($k->totalPrice,2) - round($k->deposit_price,2); // 余款
                }else{
                    $k->balancePrice = round($k->totalPrice,2); // 余款
                }
                // 查看定金      计算余款
                $order_log = WaOrdersOperateLog::find(['*'], ['order_sn_parent' => $k->order_sn, 'type' => 1]);
                $order_log = json_decode($order_log);
                if ($order_log) {
                    $result = round($sum, 2) - round($order_log->this_request_price, 2);  // 待支付余款
                    $k->balancePrice = round($result, 2);
                    $k->deposit_price = round($order_log->this_request_price, 2);
                }


                // 订单状态 0 草稿 1 待核验   2 审批中   3 待签署销售合同   4 待支付定金  5 订单采购中 6 待支付余款 7 待发货 8待收货 9 已完成 10 已作废 11 删除
                $k->status_name = IndexController::saleOrderStatusName($k->status);


                if ($k->status == 12){
                    $k->status_name = '财务确认到账';
                    $wai = WaAccountingInformation::find(['order_sn_parent' => $k->order_sn, 'type' => 1]);
                    $wai = json_decode($wai);
                    if ($wai){
                        if ($wai->status == 1){
                            $wai->accounting_information_status = 1;
                            $k->accounting_information_status_name = '待财务确认(定金)';
                        }elseif ($wai->status == 2){
                            $wai->accounting_information_status = 2;
                            $k->accounting_information_status_name = '财务已确认(定金)';
                        }elseif ($wai->status == 3){
                            $wai->accounting_information_status = 3;
                            $k->accounting_information_status_name = '到账异常(定金)';
                            $k->exception_reason = $wai->exception_reason;
                        }else{
                            $wai->accounting_information_status = '';
                            $k->accounting_information_status_name = '';
                        }
                    }
                }
                if ($k->status == 16){
                    $k->status_name = '待财务确认余款到账';
                    $wai = WaAccountingInformation::find(['order_sn_parent' => $k->order_sn, 'type' => 2]);
                    $wai = json_decode($wai);
                    if ($wai){
                        if ($wai->status == 1){
                            $wai->accounting_information_status = 1;
                            $k->accounting_information_status_name = '待财务确认(余款)';
                        }elseif ($wai->status == 2){
                            $wai->accounting_information_status = 2;
                            $k->accounting_information_status_name = '财务已确认(余款)';
                        }elseif ($wai->status == 3){
                            $wai->accounting_information_status = 3;
                            $k->accounting_information_status_name = '到账异常(余款)';
                            $k->exception_reason = $wai->exception_reason;
                        }else{
                            $wai->accounting_information_status = '';
                            $k->accounting_information_status_name = '';
                        }
                    }
                }

                // 订单类型 1 预售待采购   2  库存待销售
                if ($k->orders_type == 1) {
                    $k->orders_type_name = '预售待采购';
                } elseif ($k->orders_type == 2) {
                    $k->orders_type_name = '库存待销售';
                } elseif ($k->orders_type == 3) {
                    $k->orders_type_name = '部分预售单';
                } else {
                    $k->orders_type_name = '';
                }

                // 交货条件 1 FAS 2 FOB 3 CIF 4 CIP
//                if ($k->condition == 1) {
//                    $k->condition_name = 'FCA';
//                } elseif ($k->condition == 2) {
//                    $k->condition_name = 'FOB';
//                } elseif ($k->condition == 3) {
//                    $k->condition_name = 'CIF';
//                } elseif ($k->condition == 4) {
//                    $k->condition_name = 'CIP';
//                } else {
//                    $k->condition_name = '';
//                }
                $k->condition_name = IndexController::conditionName($k->condition);

                // 货币类型   1 人民币 2 美元 3 欧元
//                if ($k->currency == 1){
//                    $k->currency_name = '人民币';
//                }elseif ($k->currency == 2){
//                    $k->currency_name = '美元';
//                }elseif ($k->currency == 3){
//                    $k->currency_name = '欧元';
//                }else{
//                    $k->currency_name = '';
//                }

                $k->currency_name = IndexController::currencyNameCommon($k->currency);


            }
            $res = $k;

        }

        return json_encode($res);
    }

    public static function findApprove($adminId,$condition)
    {
        $res = Db::table('wa_orders_sales')
            ->where($condition)
            ->first();

        if ($res){
            $res->deposit_acc_status = 1;
            $res->deposit_acc_status_name = '未到账';
            $res->balance_acc_status = 1;
            $res->balance_acc_status_name = '未到账';
            // 入账类型 1 定金  2 余款
//                $res->type_name = '定金';
                // 定金的状态 定金未到账  定金未足额到账 定金足额到账
                $sales_fund_deposit_type_condition = [];
                $sales_fund_deposit_type_condition [] = ['order_sn_parent','=',$res->order_sn]; //
                $sales_fund_deposit_type_condition [] = ['type','=',1]; // 定金
                $sales_fund_deposit_type_where_in = [0,1]; // 待审批和通过审批
                $deposit_acc_price = WaAccountingInformationRelevance::sumsBySaesFundType($sales_fund_deposit_type_condition, $sales_fund_deposit_type_where_in);

                $sales_deposit_condition = [];
                $sales_deposit_condition [] = ['order_sn','=',$res->order_sn]; //
                $sales_data = WaOrders::find($sales_deposit_condition);
                $sales_data = json_decode($sales_data);
                if ($sales_data){
                    $deeposit_amount = $sales_data->deeposit_amount;
                }else{
                    $deeposit_amount = 0;
                }


                if (!$deposit_acc_price){
                    $res->deposit_acc_status = 1;
                    $res->deposit_acc_status_name = '未到账';
                }elseif(round($deposit_acc_price,2)>0){
                    if (round($deposit_acc_price,2) == round($deeposit_amount,2)){
                        $res->deposit_acc_status = 2;
                        $res->deposit_acc_status_name = '足额到账';
                    }else{
                        $res->deposit_acc_status = 3;
                        $res->deposit_acc_status_name = '未足额到账';
                    }
                }

//                $res->type_name = '余款';
                // 尾款的状态 尾款未到账  尾款未足额到账 尾款足额到账
                $sales_fund_balance_type_condition = [];
                $sales_fund_balance_type_condition [] = ['order_sn_parent','=',$res->order_sn]; //
                $sales_fund_balance_type_condition [] = ['type','=',2]; // 尾款
                $sales_fund_balance_type_where_in = [0,1]; // 待审批和通过审批
                $balance_acc_price= WaAccountingInformationRelevance::sumsBySaesFundType($sales_fund_balance_type_condition, $sales_fund_balance_type_where_in);

                $sales_balance_condition = [];
                $sales_balance_condition [] = ['order_sn','=',$res->order_sn]; //
                $sales_data = WaOrders::find($sales_balance_condition);
                $sales_data = json_decode($sales_data);
                if ($sales_data){
                    if ($sales_data->deeposit_amount){
                        $balance_amount = round($sales_data->total_amount,2) - round($sales_data->deeposit_amount,2);
                    }else{
                        $balance_amount = round($sales_data->total_amount,2);
                    }
                }else{
                    $balance_amount = 0;
                }

                if (!$balance_acc_price){
                    $res->balance_acc_status = 1;
                    $res->balance_acc_status_name = '未到账';
                }elseif(round($balance_acc_price,2)>0){
                    if (round($balance_acc_price,2) == $balance_amount){
                        $res->balance_acc_status = 2;
                        $res->balance_acc_status_name = '足额到账';
                    }else{
                        $res->balance_acc_status = 3;
                        $res->balance_acc_status_name = '未足额到账';
                    }
                }










            $where_bill_details = [];
            $where_bill_details [] = ['sales_order_sn', '=', $res->order_sn];
            $bill_details = WaOrdersSalesAmountDetail::all($where_bill_details);
            $acc_info_data = WaAccountingInformationRelevance::billDetailsByOrderSn($res->order_sn);
            $res->acc_info_data = $acc_info_data; //  采购账单明细
            if ($bill_details) {
                $bill_details = json_decode($bill_details);

                foreach ($bill_details as $ke) {
                    if ($ke->sales_order_sn) {
                        $where_payroll = [];
                        $where_payroll [] = ['sales_order_sn', '=', $ke->sales_order_sn];
                        $where_payroll [] = ['price_name', '=', $ke->price_name];
                        $where_payroll [] = ['module_type', '=', 2]; // 1 采购模块 2 车辆管理模块
                        $payroll_requisition = WaPurchasePayrollRequisition::allByPur($where_payroll);
                        $payroll_requisition = json_decode($payroll_requisition);


                        $ke->requested_price = WaPurchasePayrollRequisition::sums($where_payroll);
                        if ($payroll_requisition) {
                            // 总金额
                            $ke->total_amount =  round($ke->total_amount,2);
                            // 已请款
                            $ke->requested_price = round(WaPurchasePayrollRequisition::sums($where_payroll),2);
                            // 请款中
                            $ke->requested_pricing = round(WaPurchasePayrollRequisition::suming($where_payroll),2); ;
                            //  待请款
                            $ke->wait_price = $ke->total_amount - $ke->requested_price - $ke->requested_pricing;

                            $ke->payroll_requisition = $payroll_requisition;
                        } else {
                            $ke->payroll_requisition = [];
                        }

                    } else {
                        $ke->payroll_requisition = [];
                    }

                }
            }
            $res->bill_details = $bill_details; //  采购账单明细
            
            
            $approve_data = WaSalesOrdersExamineApprove::find([['sales_order_sn', '=', $res->order_sn],['status','!=',3 ]],$adminId);
            $approve_data = json_decode($approve_data);

            if ($approve_data){
                $approve = WaSalesOrdersExamineApproveFlow::all(
                    ['sales_order_sn' => $res->order_sn,'sale_no' => $approve_data->sale_no,'department_id' => $adminId->department_id,'status' => 2]);
                $approve = json_decode($approve);
                if ($approve){
                    $approve_status = 2; // 已驳回
                    $approve_status_name = '已驳回';

                }else{
                    $approve = WaSalesOrdersExamineApproveFlow::all(
                        ['sales_order_sn' => $res->order_sn,'sale_no' => $approve_data->sale_no,'department_id' => $adminId->department_id,'status' => 1]);
                    $approve = json_decode($approve);
                    if ($approve){
                        $approve_status = 1; // 已审批
                        $approve_status_name = '已审批';
                    }else{
                        $approve = WaSalesOrdersExamineApproveFlow::all(
                            ['sales_order_sn' => $res->order_sn,'sale_no' => $approve_data->sale_no,'department_id' => $adminId->department_id,'status' => 0]);
                        $approve = json_decode($approve);
                        if ($approve){
                            $approve_status = 0; // 待审批
                            $approve_status_name = '待审批';
                        }else{
                            $approve_status = 999;// 待提交审批
                            $approve_status_name = '待提交审批';
                        }
                    }

                }
            }else{
                $approve_status = 10001;// 待提交审批
                $approve_status_name = '待提交审批/或不是审批人员';
            }

            $res->approve_status = $approve_status; // 审批状态
            $res->approve_status_name = $approve_status_name;// 审批状态名称
        }


        $k = $res;
        if ($k){

//            $orders_contract = WaOrdersContract::find(['order_sn' => $k->order_sn,'status' => 3]);
//            $orders_contract = json_decode($orders_contract);
//            if (!$orders_contract){
//                $orders_contract_deeposit_amount = 0;
//            }else{
//                $orders_contract_deeposit_amount = $orders_contract->deeposit_amount;
//            }

            $sum = WaOrdersRelevance::sums(['order_sn_parent' => $k->order_sn]);
            $k->totalPrice = $sum;
//            $k->deposit_price = $orders_contract_deeposit_amount; // 定金
//            if($k->deposit_price){
//                $k->balancePrice = round($k->totalPrice,2) - round($k->deposit_price,2); // 余款
//            }else{
//                $k->balancePrice = round($k->totalPrice,2); // 余款
//            }
            // 查看定金      计算余款
            $order_log=  WaOrdersOperateLog::find(['*'],['order_sn_parent' => $k->order_sn,'type' => 1]);
            $order_log = json_decode($order_log);
            if ($order_log){
                $result =  round($sum,2) - round($order_log->this_request_price,2);  // 待支付余款
                $k->balancePrice = round($result,2);
                $k->deposit_price = round($order_log->this_request_price,2);
            }




            $k->status_name = IndexController::saleOrderStatusName($k->status);


            // 订单类型 1 预售待采购   2  库存待销售
            if ($k->orders_type == 1){
                $k->orders_type_name = '预售待采购';
            }elseif ($k->orders_type == 2){
                $k->orders_type_name = '库存待销售';
            }elseif ($k->orders_type == 3){
                $k->orders_type_name = '部分预售单';
            }else{
                $k->orders_type_name = '';
            }


            $k->condition_name = IndexController::conditionName($k->condition);


            $k->currency_name = IndexController::currencyNameCommon($k->currency);


        }
        $res = $k;



        return json_encode($res);
    }


}